package server;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.mongodb.DBObject;

public class AlexaUpdate extends Thread{
	DBObject domain;
	public AlexaUpdate(DBObject domain)
	{
		this.domain=domain;
		this.start();
	}
	public void run()
	{
		try {
			Random random = new Random();
			List<String> listSock = new ArrayList<String>();
			listSock.add("184.107.74.40");
			listSock.add("184.107.74.41");
			listSock.add("184.107.74.42");
			listSock.add("184.107.74.43");
			listSock.add("184.107.74.44");
			listSock.add("184.107.74.45");
			listSock.add("184.107.74.46");
			listSock.add("184.107.74.47");
			int rand = new Random().nextInt(7);
			Socket sockket = new Socket("alexa.com", 80, InetAddress.getByName(listSock.get(rand)), random.nextInt(1000)+30000);
//			Socket sockket = new Socket("www.alexa.com", 80);
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(sockket.getOutputStream()));
			
			writer.write("GET /siteinfo/"+domain.get("name")+" HTTP/1.1\r\n");
			writer.write("Host: www.alexa.com\r\n");
			writer.write("Referer: http://5ty.org\r\n");
			
			writer.write("User-Agent:	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1) Gecko/20100101 Firefox/8.0.1\r\n");
			writer.write("Connection:	Close\r\n");
			
			
			writer.write("\r\n\r\n");
			writer.flush();
			BufferedReader reader =  new BufferedReader(new InputStreamReader(sockket.getInputStream()));
			String content = "";
			char[] buf = new char[102102];
			int numRead=0;
	        while((numRead=reader.read(buf)) != -1){
	            String readData = String.valueOf(buf, 0, numRead);
	            content += readData;
	            buf = new char[102102];
	        }
	        reader.close();
	
			Document doc = Jsoup.parse(content);

			// visitor
			String visit = "0";
			if(doc.select(".visitors_percent").select(".avg").size() > 0)
			{
				visit = doc.select(".visitors_percent").select(".avg").last().text().trim();
			}
			// rank
			String ranks = null;
			if(doc.select("#siteStats").select("div").size() > 0)
			{
				ranks = doc.select("#siteStats").select("div").first().text().trim().replace(",","");
			}
			int rank = 0;
			
			try {
				if(ranks != null && !ranks.equals(""))
				{
					rank=Integer.parseInt( ranks );
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			
			
			//keywords
			ArrayList<String> b_key = new ArrayList<String>();
			Elements elements = doc.select("#top-keywords-from-search");

			if(elements.size() > 0)
			{
				for (Element element : elements.first().select("u")) {
					
					b_key.add(element.text().trim());
				}
			}
			
//			String speed = doc.select(".speedAd").select("p").first().text().replaceAll("[^(]+[(]+", "").replaceAll("[)]+[\\w\\W]+", "");
			
//			BasicDBObject info = new BasicDBObject();
//  			
//			DBCollection coll = Data.data("domain");
			domain.put("visit", visit);
			domain.put("lpKeyword", b_key);
			domain.put("rank", rank);
//			info.put("speed", speed);

//			BasicDBObject set = new BasicDBObject("$set", info);
//			coll.update(domain, set);
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
//	public static void main( String args[])
//	{
//		
//		Domain domain = new Domain();
//		domain.setName("google.com");
//		new AlexaUpdate(domain);
//	}
	
}
